
import logging
import os
from django.db.models import Q
from django.utils import timezone
from django.shortcuts import get_object_or_404
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from rest_framework import status, viewsets, mixins, filters
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny
from .permissions import IsOwnerAndShipper, IsAuthenticatedShipper
from rest_framework.decorators import action
from rest_framework.parsers import MultiPartParser, FormParser
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiExample, OpenApiParameter

from .models import Goods, GoodsImage
from .serializers import (
    GoodsSerializer, GoodsCreateSerializer, GoodsUpdateSerializer,
    GoodsImageSerializer, GoodsImageCreateSerializer, GoodsListSerializer
)

# 导入腾讯云COS管理类
from user_app.utils import TencentCOSManager
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import SimpleUploadedFile

logger = logging.getLogger(__name__)


@extend_schema_view(
    list=extend_schema(
        summary="获取货源列表",
        description="获取当前用户的货源列表，支持按状态和货物类型筛选，支持搜索和排序",
        tags=["Goods"],
        parameters=[
            OpenApiParameter(
                name='status',
                description='货源状态',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='goods_type',
                description='货物类型',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='search',
                description='搜索关键词（标题、描述、装货地点、卸货地点）',
                required=False,
                type=str
            ),
            OpenApiParameter(
                name='ordering',
                description='排序字段（created_at, loading_time, expected_price, weight）',
                required=False,
                type=str
            )
        ],
        examples=[
            OpenApiExample(
                '货源列表响应示例',
                summary='成功获取货源列表',
                description='返回货源列表数据',
                value={
                    "count": 1,
                    "next": None,
                    "previous": None,
                    "results": [
                        {
                            "id": 1,
                            "user_name": "13800138001",
                            "title": "沥青运输",
                            "weight": "100.00",
                            "from_location": "广州沥青厂",
                            "to_location": "深圳工地",
                            "loading_time": "2023-01-01T08:00:00Z",
                            "expected_price": "1000.00",
                            "status": "pending",
                            "status_display": "待接单",
                            "created_at": "2023-01-01T00:00:00Z"
                        }
                    ]
                },
                response_only=True,
            )
        ]
    ),
    create=extend_schema(
        summary="创建货源",
        description="创建新的货源信息，仅限通过认证的货主使用",
        tags=["Goods"],
        examples=[
            OpenApiExample(
                '创建货源请求示例',
                summary='创建货源请求',
                description='创建货源所需的请求参数',
                value={
                    "title": "沥青运输",
                    "description": "运输沥青",
                    "weight": "100.00",
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "to_location": "深圳工地",
                    "loading_time": "2023-01-01T08:00:00Z",
                    "expected_arrival_time": "2023-01-01T18:00:00Z",
                    "expected_price": "1000.00"
                },
                request_only=True,
            ),
            OpenApiExample(
                '创建货源响应示例',
                summary='成功创建货源',
                description='创建货源成功后的响应数据',
                value={
                    "id": 1,
                    "user": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "title": "沥青运输",
                    "description": "运输沥青",
                    "weight": "100.00",
                    "volume": None,
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "from_longitude": None,
                    "from_latitude": None,
                    "to_location": "深圳工地",
                    "to_longitude": None,
                    "to_latitude": None,
                    "loading_time": "2023-01-01T08:00:00Z",
                    "expected_arrival_time": "2023-01-01T18:00:00Z",
                    "expected_price": "1000.00",
                    "status": "pending",
                    "status_display": "待接单",
                    "images": [],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T00:00:00Z"
                },
                response_only=True,
            )
        ]
    ),
    retrieve=extend_schema(
        summary="获取货源详情",
        description="根据货源ID获取货源详细信息",
        tags=["Goods"],
        examples=[
            OpenApiExample(
                '货源详情响应示例',
                summary='成功获取货源详情',
                description='返回货源详细信息',
                value={
                    "id": 1,
                    "user": {
                        "id": 2,
                        "phone": "13800138001",
                        "role": "shipper",
                        "role_display": "货主",
                        "username": "shipper1",
                        "first_name": "",
                        "last_name": "",
                        "email": "",
                        "company": "广州沥青公司",
                        "credit_score": "4.80",
                        "is_active": True,
                        "date_joined": "2023-01-01T00:00:00Z",
                        "last_login": "2023-01-01T00:00:00Z"
                    },
                    "title": "沥青运输",
                    "description": "运输沥青",
                    "weight": "100.00",
                    "volume": None,
                    "goods_type": "沥青",
                    "from_location": "广州沥青厂",
                    "from_longitude": None,
                    "from_latitude": None,
                    "to_location": "深圳工地",
                    "to_longitude": None,
                    "to_latitude": None,
                    "loading_time": "2023-01-01T08:00:00Z",
                    "expected_arrival_time": "2023-01-01T18:00:00Z",
                    "expected_price": "1000.00",
                    "status": "pending",
                    "status_display": "待接单",
                    "images": [],
                    "created_at": "2023-01-01T00:00:00Z",
                    "updated_at": "2023-01-01T00:00:00Z"
                },
                response_only=True,
            )
        ]
    ),
)
class GoodsViewSet(viewsets.GenericViewSet,
                   mixins.CreateModelMixin,
                   mixins.ListModelMixin,
                   mixins.RetrieveModelMixin):
    """货源视图集"""
    
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['status', 'goods_type']
    search_fields = ['title', 'description', 'from_location', 'to_location']
    ordering_fields = ['created_at', 'loading_time', 'expected_price', 'weight']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据操作选择序列化器"""
        if self.action == 'create':
            return GoodsCreateSerializer
        elif self.action == 'list':
            return GoodsListSerializer
        elif self.action == 'update_goods':
            return GoodsUpdateSerializer
        return self.serializer_class
    
    def get_permissions(self):
        """根据操作选择权限"""
        if self.action == 'list' or self.action == 'retrieve':
            # 列表和详情操作需要认证用户
            return [IsAuthenticated()]
        elif self.action == 'update_goods':
            # 更新操作需要货主本人且已通过认证
            return [IsAuthenticated(), IsOwnerAndShipper()]
        elif self.action == 'create':
            # 创建操作需要是已认证的货主
            return [IsAuthenticated(), IsAuthenticatedShipper()]
        return super().get_permissions()
    
    def get_queryset(self):
        """获取查询集"""
        queryset = super().get_queryset()
        
        # 货源列表仅返回当前用户创建的货源
        if self.action == 'list':
            return queryset.filter(user=self.request.user)
        
        return queryset
    
    def perform_create(self, serializer):
        """创建货源时设置用户"""
        return serializer.save(user=self.request.user)
    
    def create(self, request, *args, **kwargs):
        """重写create方法以确保返回包含ID的完整货物信息"""
        logger.info(f"收到创建货源请求: {request.data}")
        try:
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            instance = self.perform_create(serializer)
            
            # 使用GoodsSerializer序列化响应数据，确保包含ID等完整信息
            response_serializer = GoodsSerializer(instance)
            headers = self.get_success_headers(response_serializer.data)
            
            logger.info(f"货源创建成功: {response_serializer.data}")
            return Response(response_serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        except Exception as e:
            logger.error(f"货源创建失败: {str(e)}", exc_info=True)
            raise
    
    def retrieve(self, request, *args, **kwargs):
        """重写retrieve方法以支持'me'参数"""
        # 检查是否使用'me'参数
        if kwargs.get('pk') == 'me':
            # 返回当前用户的所有货物
            queryset = self.get_queryset().filter(user=request.user)
            
            # 序列化数据
            serializer = GoodsListSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            # 使用默认的retrieve方法
            return super().retrieve(request, *args, **kwargs)

    @action(detail=True, methods=['post'])
    def update_goods(self, request, pk=None):
        """更新货源信息"""
        # 检查是否使用'me'参数
        if pk == 'me':
            return Response(
                {'error': '无法对"me"参数更新货物，请指定具体的货物ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        goods = self.get_object()
        
        # 检查是否是货源的所有者
        if goods.user != request.user:
            return Response(
                {'error': '只有货源的所有者才能更新货源信息'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        # 使用更新序列化器
        serializer = self.get_serializer(goods, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            # 返回完整信息
            response_serializer = GoodsSerializer(goods)
            return Response(response_serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def delete_goods(self, request, pk=None):
        """删除货源"""
        # 检查是否使用'me'参数
        if pk == 'me':
            return Response(
                {'error': '无法对"me"参数删除货物，请指定具体的货物ID'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        goods = self.get_object()
        
        # 检查是否是货源的所有者
        if goods.user != request.user:
            return Response(
                {'error': '只有货源的所有者才能删除货源'},
                status=status.HTTP_403_FORBIDDEN
            )
        
        goods.delete()
        
        return Response({'message': '货源删除成功'}, status=status.HTTP_200_OK)
